import * as vscode from "vscode";
import { KeyReplacer } from "./keyReplacer";
import { DynamicFunctionManager } from './dynamicFunctionManager';
import * as path from "path";
import * as fs from "fs";
let dynamicFunctionManager: DynamicFunctionManager;
export function activate(context: vscode.ExtensionContext) {
    console.log("Key Replacer extension is now active");

    // 获取配置
    const config = vscode.workspace.getConfiguration("keyReplacer");
    const mappingFileName: string = config.get(
        "mappingFileName",
        "key-mapping.json"
    );

    // 确定映射文件路径
    let mappingFilePath = mappingFileName;
    if (
        vscode.workspace.workspaceFolders &&
        !path.isAbsolute(mappingFileName)
    ) {
        mappingFilePath = path.join(
            vscode.workspace.workspaceFolders[0].uri.fsPath,
            mappingFileName
        );
    }

    // 创建KeyReplacer实例
    const keyReplacer = new KeyReplacer(mappingFilePath);
    dynamicFunctionManager = new DynamicFunctionManager(context);

    // 注册命令 - 替换并保存整个工作区
    const replaceKeysCommand = vscode.commands.registerCommand(
        "key-replacer.replaceKeys",
        async () => {
            try {
                const result = await keyReplacer.replaceAndSaveInWorkspace();
                vscode.window.showInformationMessage(
                    `处理完成: ${result.processed} 个文件, ${result.modified} 个被修改, ${result.saved} 个已保存`
                );
            } catch (error) {
                vscode.window.showErrorMessage(
                    `Error during key replacement: ${error}`
                );
            }
        }
    );

    // 注册命令 - 替换并保存当前文件
    const replaceKeysInFileCommand = vscode.commands.registerCommand(
        "key-replacer.replaceKeysInFile",
        async () => {
            const editor = vscode.window.activeTextEditor;
            if (!editor) {
                vscode.window.showErrorMessage("No active editor");
                return;
            }

            try {
                const modified = await keyReplacer.replaceAndSaveFile(
                    editor.document
                );
                if (modified) {
                    vscode.window.showInformationMessage(
                        "文件替换完成并已保存"
                    );
                } else {
                    vscode.window.showInformationMessage(
                        "No keys to replace in current file"
                    );
                }
            } catch (error) {
                vscode.window.showErrorMessage(
                    `Error replacing keys: ${error}`
                );
            }
        }
    );

    // 注册命令 - 替换当前文件但不保存（保持原有行为）
    const replaceKeysInFileWithoutSaveCommand = vscode.commands.registerCommand(
        "key-replacer.replaceKeysInFileWithoutSave",
        async () => {
            const editor = vscode.window.activeTextEditor;
            if (!editor) {
                vscode.window.showErrorMessage("No active editor");
                return;
            }

            try {
                const modified = await keyReplacer.replaceInFile(
                    editor.document
                );
                if (modified) {
                    vscode.window.showInformationMessage(
                        "文件替换完成"
                    );
                } else {
                    vscode.window.showInformationMessage(
                        "No keys to replace in current file"
                    );
                }
            } catch (error) {
                vscode.window.showErrorMessage(
                    `Error replacing keys: ${error}`
                );
            }
        }
    );

    // 注册命令 - 生成或更新映射文件
    const generateMappingCommand = vscode.commands.registerCommand(
        "key-replacer.generateMapping",
        async () => {
            try {
                const generated = await keyReplacer.generateOrUpdateMapping();
                if (generated) {
                    // 重新加载映射
                    keyReplacer.reloadMapping();
                }
            } catch (error) {
                vscode.window.showErrorMessage(
                    `Error generating mapping: ${error}`
                );
            }
        }
    );

    // 注册命令 - 从当前文件提取中文键
    const extractKeysFromFileCommand = vscode.commands.registerCommand(
        "key-replacer.extractKeysFromFile",
        async () => {
            const editor = vscode.window.activeTextEditor;
            if (!editor) {
                vscode.window.showErrorMessage("No active editor");
                return;
            }

            try {
                const chineseKeys =
                    await keyReplacer.extractChineseKeysFromFile(
                        editor.document
                    );
                if (chineseKeys.length > 0) {
                    vscode.window.showInformationMessage(
                        `从当前文件提取到 ${
                            chineseKeys.length
                        } 中文键: ${chineseKeys.join(
                            ", "
                        )}`
                    );
                } else {
                    vscode.window.showInformationMessage(
                        "No Chinese keys found in current file"
                    );
                }
            } catch (error) {
                vscode.window.showErrorMessage(
                    `Error extracting keys: ${error}`
                );
            }
        }
    );

    // 注册命令 - 从整个工作区提取中文键
    const extractKeysFromWorkspaceCommand = vscode.commands.registerCommand(
        "key-replacer.extractKeysFromWorkspace",
        async () => {
            try {
                const chineseKeys =
                    await keyReplacer.extractChineseKeysFromWorkspace();
                if (chineseKeys.length > 0) {
                    // 显示前10个键
                    const displayKeys = chineseKeys.slice(0, 10);
                    const message =
                        chineseKeys.length > 10
                            ? `Found ${
                                  chineseKeys.length
                              } Chinese keys. First 10: ${displayKeys.join(
                                  ", "
                              )}`
                            : `Found ${
                                  chineseKeys.length
                              } Chinese keys: ${chineseKeys.join(", ")}`;

                    vscode.window.showInformationMessage(message);
                } else {
                    vscode.window.showInformationMessage(
                        "No Chinese keys found in workspace"
                    );
                }
            } catch (error) {
                vscode.window.showErrorMessage(
                    `Error extracting keys: ${error}`
                );
            }
        }
    );

    const createMappingFileCommand = vscode.commands.registerCommand(
        "key-replacer.createMappingFile",
        async () => {
            if (!vscode.workspace.workspaceFolders) {
                vscode.window.showErrorMessage("No workspace folder open");
                return;
            }

            const workspacePath =
                vscode.workspace.workspaceFolders[0].uri.fsPath;
            const mappingFilePath = path.join(workspacePath, mappingFileName);

            // 检查文件是否已存在
            if (fs.existsSync(mappingFilePath)) {
                const overwrite = await vscode.window.showWarningMessage(
                    `Mapping file ${mappingFileName} already exists. Overwrite?`,
                    "Yes",
                    "No"
                );

                if (overwrite !== "Yes") {
                    return;
                }
            }

            // 创建示例映射文件
            const sampleMapping = {
                "[用户]": "user",
                "[管理员]": "admin",
                "[订单]": "order",
                "[商品]": "product",
            };

            try {
                fs.writeFileSync(
                    mappingFilePath,
                    JSON.stringify(sampleMapping, null, 2),
                    "utf-8"
                );

                // 在编辑器中打开文件
                const document = await vscode.workspace.openTextDocument(
                    mappingFilePath
                );
                await vscode.window.showTextDocument(document);

                vscode.window.showInformationMessage(
                    `Created mapping file: ${mappingFileName}`
                );
            } catch (error) {
                vscode.window.showErrorMessage(
                    `Error creating mapping file: ${error}`
                );
            }
        }
    );

    const reloadMappingCommand = vscode.commands.registerCommand(
        "key-replacer.reloadMapping",
        () => {
            keyReplacer.reloadMapping();
            vscode.window.showInformationMessage("Key mapping reloaded");
        }
    );
     const showDynamicMenu = vscode.commands.registerCommand('key-replacer.showDynamicMenu', async () => {
        await dynamicFunctionManager.showFunctionMenu();
    });

    // 注册所有命令
    context.subscriptions.push(
        replaceKeysCommand,
        replaceKeysInFileCommand,
        replaceKeysInFileWithoutSaveCommand,
        generateMappingCommand,
        extractKeysFromFileCommand,
        extractKeysFromWorkspaceCommand,
        createMappingFileCommand,
        reloadMappingCommand,
        showDynamicMenu
    );

    // 监听映射文件变化
    if (vscode.workspace.workspaceFolders) {
        const fileWatcher = vscode.workspace.createFileSystemWatcher(
            new vscode.RelativePattern(
                vscode.workspace.workspaceFolders[0],
                mappingFileName
            )
        );

        fileWatcher.onDidChange(() => {
            keyReplacer.reloadMapping();
        });

        fileWatcher.onDidCreate(() => {
            keyReplacer.reloadMapping();
        });

        context.subscriptions.push(fileWatcher);
    }
}

export function deactivate() {
    console.log("Key Replacer extension is now deactivated");
}
